package com.whfc.fuum.manager.impl;

import com.whfc.common.enums.JoinType;
import com.whfc.common.enums.SysUserType;
import com.whfc.common.exception.BizException;
import com.whfc.common.util.DateUtil;
import com.whfc.fuum.dao.SysDeptUserMapper;
import com.whfc.fuum.dao.SysUserMapper;
import com.whfc.fuum.dao.SysUserRoleMapper;
import com.whfc.fuum.entity.SysDeptUser;
import com.whfc.fuum.entity.SysUser;
import com.whfc.fuum.manager.SysUserManager;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

/**
 * @ClasssName SysUserManagerImpl
 * @Description
 * @Author hw
 * @Date 2020/12/25 15:35
 * @Version 1.0
 */
@Service
public class SysUserManagerImpl implements SysUserManager {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysDeptUserMapper sysDeptUserMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    public SysUser getUserByPhone(String phone) throws BizException {
        return sysUserMapper.selectByPhone(phone);
    }

    @Override
    public void saveInviterUserRule(String nickName, String phone, Integer deptId, Integer inviterUserId) throws BizException {
        SysUser sysUser = sysUserMapper.selectByPhone(phone);
        if (sysUser == null) {
            sysUser = new SysUser();
            sysUser.setPhone(phone);
            sysUser.setUsername(phone);
            if (StringUtils.isEmpty(nickName)) {
                nickName = phone;
            }
            sysUser.setNickname(nickName + "(邀请加入)");
            sysUser.setType(SysUserType.EXPERIENCE.getValue());
            sysUser.setExpireTime(DateUtil.addDays(new Date(), 7));
            String salt = UUID.randomUUID().toString().replaceAll("-", "");
            String encryptedPassword = new SimpleHash("MD5", phone, salt).toString();
            sysUser.setPassword(encryptedPassword);
            sysUser.setSalt(salt);
            sysUserMapper.insertSelective(sysUser);
        }
        SysDeptUser sysDeptUser = new SysDeptUser();
        sysDeptUser.setDeptId(deptId);
        sysDeptUser.setUserId(sysUser.getId());
        sysDeptUser.setJoinType(JoinType.INVITE.value());
        sysDeptUserMapper.insertSelective(sysDeptUser);
        sysUserRoleMapper.copyUserRuleBYDeptIdAndInviterUserId(sysUser.getId(), deptId, inviterUserId);
    }
}
